/*
 * Copyright (c) 2024-2025.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.leafage.exploiter.service.impl;

import io.leafage.exploiter.domain.MasterPlate;
import io.leafage.exploiter.dto.MasterPlateDTO;
import io.leafage.exploiter.repository.MasterPlateRepository;
import io.leafage.exploiter.service.MasterPlateService;
import io.leafage.exploiter.vo.MasterPlateVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.StreamSupport;

@Service
public class MasterPlateServiceImpl implements MasterPlateService {

    private final MasterPlateRepository masterPlateRepository;

    public MasterPlateServiceImpl(MasterPlateRepository masterPlateRepository) {
        this.masterPlateRepository = masterPlateRepository;
    }

    @Override
    public Page<MasterPlateVO> retrieve(int page, int size, String sortBy, boolean descending, String name) {
        Sort sort = Sort.by(descending ? Sort.Direction.DESC : Sort.Direction.ASC,
                StringUtils.hasText(sortBy) ? sortBy : "id");
        Pageable pageable = PageRequest.of(page, size, sort);

        if (StringUtils.hasText(name)) {
            return masterPlateRepository.findAllByNameContaining(name, pageable)
                    .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class));
        }
        return masterPlateRepository.findAll(pageable)
                .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class));
    }

    @Override
    public List<MasterPlateVO> retrieve(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return masterPlateRepository.findAll().stream()
                    .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class)).toList();
        } else {
            return masterPlateRepository.findAllById(ids).stream()
                    .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class)).toList();
        }
    }

    @Override
    public MasterPlateVO fetch(Long id) {
        return masterPlateRepository.findById(id)
                .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class)).orElse(null);
    }

    @Override
    public MasterPlateVO create(MasterPlateDTO dto) {
        MasterPlate masterPlate = convertToDomain(dto, MasterPlate.class);
        masterPlateRepository.save(masterPlate);
        return convertToVO(masterPlate, MasterPlateVO.class);
    }

    @Override
    public List<MasterPlateVO> createAll(Iterable<MasterPlateDTO> iterable) {
        List<MasterPlate> masterPlates = StreamSupport.stream(iterable.spliterator(), false)
                .map(dto -> convertToDomain(dto, MasterPlate.class)).toList();
        return masterPlateRepository.saveAll(masterPlates).stream()
                .map(masterPlate -> convertToVO(masterPlate, MasterPlateVO.class)).toList();
    }

    @Override
    public MasterPlateVO modify(Long id, MasterPlateDTO dto) {
        Assert.notNull(id, "id must not be null.");

        return masterPlateRepository.findById(id)
                .map(existing -> {
                    MasterPlate masterPlate = convert(dto, existing);
                    masterPlate = masterPlateRepository.save(masterPlate);
                    return convertToVO(masterPlate, MasterPlateVO.class);
                })
                .orElseThrow();
    }

    @Override
    public void remove(Long id) {
        Assert.notNull(id, "id must not be null.");

        masterPlateRepository.deleteById(id);
    }

    @Override
    public boolean exists(String name, String suffix, String version, Long id) {
        if (id == null) {
            return masterPlateRepository.existsByNameAndSuffixAndVersion(name, suffix, version);
        }
        return masterPlateRepository.existsByNameAndSuffixAndVersionAndIdNot(name, suffix, version, id);
    }

    @Override
    public boolean enable(Long id) {
        return masterPlateRepository.updateEnabledById(id) > 0;
    }

}
